﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Classes;
using VAdvantage.Logging;
using System.Data;
using VAdvantage.DataBase;
using System.IO;
using VAdvantage.Model;

using VAdvantage.Framework;
using System.ServiceModel;
using System.ServiceModel.Channels;
using VAdvantage.GlobalWeatherService;
using VAdvantage.CountryService;

namespace VAdvantage.Utility
{
    public class AEnv
    {

        /** Workflow Menu		*/
        private static bool? _workflow = null;
        /** Workflow Menu		*/
        private static int workflowWindowID = 0;

        /**	Window Cache		*/
        private static CCache<int, GridWindowVO> s_windows
            = new CCache<int, GridWindowVO>("AD_Window", 10);

        /* SilverLight Window Cache */
        /* Sales Order ,Request,Lead, Product etc*/

        //DO NOT CHANGE WEATHER SERVICE PATH
        private static string GlobalWeatherURL = "http://www.webservicex.net/globalweather.asmx";
        private static string CountryURL = "http://www.webservicex.net/country.asmx";

        //Modified by Jagmohna bhatt. ServiceConfig.ClientConfig file will not be used any more.
        //Web Service path will be picked from the application host path
        private static string DSProcessWorkflowURL = "../VAdvantageSvc/DSProcessWorkflow.svc";
        private static string ExcelImportService = "../VAdvantageSvc/ExcelImportService.svc";
        private static string DataServicesURL = "../VAdvantageSvc/DataServices.svc";
        private static string DataServiceBasicURL = "../VAdvantageSvc/DataServiceBasic.svc";
        private static string DataServiceBasic2URL = "../VAdvantageSvc/DataServiceBasic2.svc";
        private static string DSPostingURL = "../VAdvantageSvc/DSPosting.svc";
        private static string DataServiceDBURL = "../VAdvantageSvc/DataServiceDB.svc";
        private static string AcctServiceURL = "http://192.168.0.90/CloudService55/AccountService.asmx";

        private static VLogger log = VLogger.GetVLogger(typeof(AEnv).FullName);

        /// <summary>
        /// Get Window Model object from cache 
        /// </summary>
        /// <param name="WindowNo">window Number </param>
        /// <param name="AD_Window_ID">window id </param>
        /// <param name="AD_Menu_ID"> menu id </param>
        /// <returns>return windowVo if found</returns>
        public static GridWindowVO GetMWindowVO(int windowNo, int AD_Window_ID, int AD_Menu_ID)
        {
            log.Config("Window=" + windowNo + ", AD_Window_ID=" + AD_Window_ID);
            GridWindowVO mWindowVO = null;

            //if (AD_Window_ID != 0)
            //{
            //    mWindowVO = s_windowsSpecial[AD_Window_ID];
            //    if (mWindowVO != null)
            //    {
            //        mWindowVO = mWindowVO.Clone(windowNo);
            //        log.Info("Cached=" + mWindowVO);
            //    }
            //}


            if (AD_Window_ID != 0 && Ini.IsCacheWindow())	//	try cache
            {
                mWindowVO = s_windows[AD_Window_ID];
                if (mWindowVO != null)
                {
                    mWindowVO = mWindowVO.Clone(windowNo);
                    log.Info("Cached=" + mWindowVO);
                }
            }
            //  try to get from Server when enabled
            //if (mWindowVO == null && DB.isRemoteObjects() && isServerActive())
            //{
            //    log.config("trying server");
            //    try
            //    {
            //        s_server = CConnection.get().getServer();
            //        if (s_server != null)
            //        {
            //            mWindowVO = s_server.getWindowVO(Env.getCtx(), WindowNo, AD_Window_ID, AD_Menu_ID);
            //            log.config("from Server: success");
            //        }
            //    }
            //    catch (RemoteException e)
            //    {
            //        log.log(Level.SEVERE, "(RE)", e);
            //        mWindowVO = null;
            //        s_server = null;
            //    }
            //    catch (Exception e)
            //    {
            //        Throwable tt = e.getCause();
            //        if (tt != null && tt instanceof InvalidClassException)
            //            log.log(Level.SEVERE, "(Server<>Client class) " + tt);
            //        else if (tt != null && tt instanceof NotSerializableException)
            //            log.log(Level.SEVERE, "Serialization: " + tt.getMessage(), e);
            //        else
            //            log.log(Level.SEVERE, "ex", e);
            //        mWindowVO = null;
            //        s_server = null;
            //    }
            //    catch (Throwable t)
            //    {
            //        log.log(Level.SEVERE, t.toString());
            //        mWindowVO = null;
            //        s_server = null;
            //    }
            //    if (mWindowVO != null)
            //        s_windows.put(AD_Window_ID, mWindowVO);
            //}	//	from Server

            //  Create Window Model on Client
            if (mWindowVO == null)
            {
                //log.Config("create local");
                //if (System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.ISALL_SAVED] == "Y")
                //{
                   // log.Info("local database");
                    mWindowVO = GridWindowVO.Create(Utility.Envs.GetCtx(), windowNo, AD_Window_ID, AD_Menu_ID, "Silverlight");
                //}
                //else
                //{
                //    log.Info("direct Database");
                //    mWindowVO = GridWindowVO.Create(Utility.Envs.GetCtx(), windowNo, AD_Window_ID, AD_Menu_ID);
                //}

                if (mWindowVO != null)
                    s_windows[AD_Window_ID] = mWindowVO;
            }	//	from Client
            if (mWindowVO == null)
                return null;

            //  Check (remote) context
            Utility.Ctx ctx = Utility.Envs.GetContext();
            if (!mWindowVO.ctx.Equals(ctx))
            {
                ////  Remote Context is called by value, not reference
                ////  Add Window properties to context
                //  mWindowVO.ctx.EntrySet()
                //Iterator<Map.Entry<String,String>> it = set.iterator();
                //while (it.hasNext())
                //{
                //    Map.Entry<String,String> entry = it.next();
                //    String key = entry.getKey();
                //    if (key.startsWith(WindowNo+"|"))
                //    {
                //        String value = entry.getValue();
                //        ctx.setContext(key, value);
                //    }
                //}
                ////  Sync Context
                //mWindowVO.setCtx(Env.getCtx());
            }
            return mWindowVO;
        }   //  getWindow
        //public static GridWindowVO GetMWindowVO(int windowNo, int AD_Window_ID, int AD_Menu_ID,string SL)
        //{
        //    log.Config("Window=" + windowNo + ", AD_Window_ID=" + AD_Window_ID);
        //    GridWindowVO mWindowVO = null;

        //    //if (AD_Window_ID != 0)
        //    //{

        //    //    mWindowVO = s_windowsSpecial[AD_Window_ID];
        //    //    if (mWindowVO != null)
        //    //    {
        //    //        mWindowVO = mWindowVO.Clone(windowNo);
        //    //    }
        //    //}


        //    if (AD_Window_ID != 0 && Ini.IsCacheWindow())	//	try cache
        //    {
        //        mWindowVO = s_windows[AD_Window_ID];
        //        if (mWindowVO != null)
        //        {
        //            mWindowVO = mWindowVO.Clone(windowNo);
        //            log.Info("Cached=" + mWindowVO);
        //        }
        //    }
        //    //  try to get from Server when enabled
        //    //if (mWindowVO == null && DB.isRemoteObjects() && isServerActive())
        //    //{
        //    //    log.config("trying server");
        //    //    try
        //    //    {
        //    //        s_server = CConnection.get().getServer();
        //    //        if (s_server != null)
        //    //        {
        //    //            mWindowVO = s_server.getWindowVO(Env.getCtx(), WindowNo, AD_Window_ID, AD_Menu_ID);
        //    //            log.config("from Server: success");
        //    //        }
        //    //    }
        //    //    catch (RemoteException e)
        //    //    {
        //    //        log.log(Level.SEVERE, "(RE)", e);
        //    //        mWindowVO = null;
        //    //        s_server = null;
        //    //    }
        //    //    catch (Exception e)
        //    //    {
        //    //        Throwable tt = e.getCause();
        //    //        if (tt != null && tt instanceof InvalidClassException)
        //    //            log.log(Level.SEVERE, "(Server<>Client class) " + tt);
        //    //        else if (tt != null && tt instanceof NotSerializableException)
        //    //            log.log(Level.SEVERE, "Serialization: " + tt.getMessage(), e);
        //    //        else
        //    //            log.log(Level.SEVERE, "ex", e);
        //    //        mWindowVO = null;
        //    //        s_server = null;
        //    //    }
        //    //    catch (Throwable t)
        //    //    {
        //    //        log.log(Level.SEVERE, t.toString());
        //    //        mWindowVO = null;
        //    //        s_server = null;
        //    //    }
        //    //    if (mWindowVO != null)
        //    //        s_windows.put(AD_Window_ID, mWindowVO);
        //    //}	//	from Server

        //    //  Create Window Model on Client
        //    if (mWindowVO == null)
        //    {
        //        log.Config("create local");
        //        mWindowVO = GridWindowVO.Create(Utility.Envs.GetCtx(), windowNo, AD_Window_ID, AD_Menu_ID,SL);
        //        if (mWindowVO != null)
        //            s_windows[AD_Window_ID] = mWindowVO;
        //    }	//	from Client
        //    if (mWindowVO == null)
        //        return null;

        //    //  Check (remote) context
        //    Utility.Ctx ctx = Utility.Envs.GetContext();
        //    if (!mWindowVO.ctx.Equals(ctx))
        //    {
        //        ////  Remote Context is called by value, not reference
        //        ////  Add Window properties to context
        //        //  mWindowVO.ctx.EntrySet()
        //        //Iterator<Map.Entry<String,String>> it = set.iterator();
        //        //while (it.hasNext())
        //        //{
        //        //    Map.Entry<String,String> entry = it.next();
        //        //    String key = entry.getKey();
        //        //    if (key.startsWith(WindowNo+"|"))
        //        //    {
        //        //        String value = entry.getValue();
        //        //        ctx.setContext(key, value);
        //        //    }
        //        //}
        //        ////  Sync Context
        //        //mWindowVO.setCtx(Env.getCtx());
        //    }
        //    return mWindowVO;
        //}   //  getWindow

        /// <summary>
        /// Zoom
        /// </summary>
        /// <param name="AD_Table_ID">table id</param>
        /// <param name="Record_ID">record id</param>
        public static void Zoom(int AD_Table_ID, int Record_ID)
        {
            String tableName = null;
            int AD_Window_ID = 0;
            int PO_Window_ID = 0;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                String sql = "SELECT TableName, AD_Window_ID, PO_Window_ID FROM AD_Table WHERE AD_Table_ID=" + AD_Table_ID;
                IDataReader dr = null;
                try
                {
                    dr = DB.ExecuteReader(sql);
                    if (dr.Read())
                    {
                        tableName = dr[0].ToString();
                        AD_Window_ID = Utility.Util.GetValueOfInt(dr[1].ToString());
                        PO_Window_ID = Utility.Util.GetValueOfInt(dr[2].ToString());
                    }
                    dr.Close();
                }
                catch (Exception e)
                {
                    if (dr != null)
                    {
                        dr.Close();
                    }
                    log.Log(Level.SEVERE, sql, e);
                }
                //  Nothing to Zoom to
                if (tableName == null || AD_Window_ID == 0)
                {
                    log.Info("No window/Form --> open table window and bind a window to that table");
                    return;
                }

                //	PO Zoom ?
                if (PO_Window_ID != 0)
                {
                    String whereClause = tableName + "_ID=" + Record_ID;

                    AD_Window_ID = ZoomTarget.GetZoomAD_Window_ID(tableName, 0, whereClause, true);

                    if (AD_Window_ID == 0)
                        return;
                }

                log.Config(tableName + " - Record_ID=" + Record_ID);

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                 {
                     //GenerateWindow frame = new GenerateWindow();
                     Apps.AWindow frame = new VAdvantage.Apps.AWindow();
                     // get window
                     //Framework.VForm obj = frame.InitilizeWindow(Query.GetEqualQuery(tableName + "_ID", Record_ID), false, AD_Window_ID);
                     if (frame.InitWindow(AD_Window_ID, Query.GetEqualQuery(tableName + "_ID", Record_ID)))
                     {
                         // show the window
                         //frame.StartPosition = FormStartPosition.CenterScreen;//silverlight comment
                         frame.Show();
                     }
                     //obj = null;
                     frame = null;

                 });
            });








        }


        private static bool? _isEmployee = null;

        public static bool IsUserEmployee()
        {
            if (_isEmployee == null)
            {
                Ctx _ctx = Utility.Envs.GetCtx();
                MUser user = MUser.Get(_ctx, _ctx.GetAD_User_ID());
                MBPartner bp = MBPartner.Get(Utility.Envs.GetCtx(), user.GetC_BPartner_ID());
                user = null;
                if (bp == null)
                {
                    _isEmployee = false;
                }
                else
                {
                    _isEmployee = bp.IsEmployee();
                }
            }
            return (bool)_isEmployee;
        }



        /// <summary>
        /// Is Workflow Process view enabled.
        /// </summary>
        /// <returns>true if enabled</returns>
        public static bool IsWorkflowProcess()
        {
            if (_workflow == null)
            {
                _workflow = false;
                int AD_Table_ID = 645;	//	AD_WF_Process	
                if (MRole.GetDefault().IsTableAccess(AD_Table_ID, true))	//	RO
                    _workflow = true;
                else
                {
                    AD_Table_ID = 644;	//	AD_WF_Activity	
                    if (MRole.GetDefault().IsTableAccess(AD_Table_ID, true))	//	RO
                        _workflow = true;
                    else
                        log.Config(_workflow.ToString());
                }
                //	Get Window
                if ((bool)_workflow)
                {
                    //workflowWindowID = DataBase.getSQLValue(null,
                    //    "SELECT AD_Window_ID FROM AD_Table WHERE AD_Table_ID=?", AD_Table_ID);
                    string sql = "SELECT AD_Window_ID FROM AD_Table WHERE AD_Table_ID=" + AD_Table_ID;
                    workflowWindowID = Convert.ToInt32(DataBase.DB.ExecuteScalar(sql));
                    if (workflowWindowID == 0)
                        workflowWindowID = 297;	//	fallback HARDCODED
                    log.Config(_workflow + ", Window=" + workflowWindowID);
                }
            }
            return (bool)_workflow;
        }

        /// <summary>
        /// Start Workflow Process Window
        /// </summary>
        /// <param name="AD_Table_ID">optional table</param>
        /// <param name="Record_ID">optional record</param>
        public static void StartWorkflowProcess(int AD_Table_ID, int Record_ID)
        {
            if (workflowWindowID == 0)
            {
                return;
            }
            //
            Query query = null;
            if (AD_Table_ID != 0 && Record_ID != 0)
            {
                query = new Query("AD_WF_Process");
                query.AddRestriction("AD_Table_ID", Query.EQUAL, AD_Table_ID);
                query.AddRestriction("Record_ID", Query.EQUAL, Record_ID);
            }
            //
            //GenerateWindow frame = new GenerateWindow();

            Apps.AWindow frame = new VAdvantage.Apps.AWindow();
            // get window
            //Framework.VForm obj = frame.InitilizeWindow(query, false, workflowWindowID);
            if (frame.InitWindow(workflowWindowID, query))
            {
                // show the window
                //frame.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                // frame.Show();
            }
            // obj = null;
            frame = null;
        }




       

        public static DataService.DataServicesClient GetDataServiceTcpClient()
        {
            return new DataService.DataServicesClient();
        }


        public static ExcelImportService.ExcelImportServiceClient GetExcelImportService()
        {
            EndpointAddress endpoint = new EndpointAddress(ExcelImportService);
            PollingDuplexHttpSecurityMode mode = PollingDuplexHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = PollingDuplexHttpSecurityMode.Transport;

            PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding(mode, PollingDuplexMode.SingleMessagePerPoll)
            {
                CloseTimeout = new TimeSpan(00, 45, 00),
                SendTimeout = new TimeSpan(00, 45, 00),
                OpenTimeout = new TimeSpan(00, 45, 00),
                ReceiveTimeout = new TimeSpan(00, 45, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;

            return new ExcelImportService.ExcelImportServiceClient(binding, endpoint);

            //return new DSProcessWorkflow.DSProcessWorkflowClient();
        }

        public static DSProcessWorkflow.DSProcessWorkflowClient GetDSPWFClient()
        {
            EndpointAddress endpoint = new EndpointAddress(DSProcessWorkflowURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;

            return new DSProcessWorkflow.DSProcessWorkflowClient(binding, endpoint);

            //return new DSProcessWorkflow.DSProcessWorkflowClient();
        }

        public static DSPosting.DSPostingClient GetDSPostingClient()
        {
            EndpointAddress endpoint = new EndpointAddress(DSPostingURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DSPosting.DSPostingClient(binding, endpoint);
            //return new DSPosting.DSPostingClient();
        }

        public static DataServiceBasic.DataServicesBasicClient GetDataServiceBasicClient()
        {
            EndpointAddress endpoint = new EndpointAddress(DataServiceBasicURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;
                
            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DataServiceBasic.DataServicesBasicClient(binding, endpoint);
            //return new DataServiceBasic.DataServicesBasicClient();

        }

        public static DataServiceBasic2.DataServicesBasic2Client GetDataServiceBasic2Client()
        {
            EndpointAddress endpoint = new EndpointAddress(DataServiceBasic2URL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DataServiceBasic2.DataServicesBasic2Client(binding, endpoint);

            //return new DataServiceBasic2.DataServicesBasic2Client();
        }
        public static DataService.DataServicesClient GetDataServiceClient()
        {
            EndpointAddress endpoint = new EndpointAddress(DataServicesURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DataService.DataServicesClient(binding, endpoint);

            //var client = new DataService.DataServicesClient();
            //Channel.AsDisposable(client);
            //return client;
        }


        public static System.Data.SqlClient.DataServicesDBClient GetDataServiceDBClient()
        {

            EndpointAddress endpoint = new EndpointAddress(DataServiceDBURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue

            };

            binding.Security.Mode = mode;
            return new System.Data.SqlClient.DataServicesDBClient(binding, endpoint);
        }

        public static GlobalWeatherSoapClient GetGlobalWeatherSoapClient()
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
            {
                CloseTimeout = new TimeSpan(00, 10, 00),
                SendTimeout = new TimeSpan(00, 10, 00),
                OpenTimeout = new TimeSpan(00, 10, 00),
                ReceiveTimeout = new TimeSpan(00, 10, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };
            return new GlobalWeatherSoapClient(binding, new EndpointAddress(GlobalWeatherURL));
        }

        public static countrySoapClient GetcountrySoapClient()
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
            {
                CloseTimeout = new TimeSpan(00, 10, 00),
                SendTimeout = new TimeSpan(00, 10, 00),
                OpenTimeout = new TimeSpan(00, 10, 00),
                ReceiveTimeout = new TimeSpan(00, 10, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };
            return new countrySoapClient(binding, new EndpointAddress(CountryURL));
        }



        public static DataServiceBasic.DataServicesBasicClient GetDataServiceBasicClient(int minute)
        {
            EndpointAddress endpoint = new EndpointAddress(DataServiceBasicURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, minute, 00),
                SendTimeout = new TimeSpan(00, minute, 00),
                OpenTimeout = new TimeSpan(00, minute, 00),
                ReceiveTimeout = new TimeSpan(00, minute, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DataServiceBasic.DataServicesBasicClient(binding, endpoint);
            //return new DataServiceBasic.DataServicesBasicClient();

        }

        public static DataServiceBasic2.DataServicesBasic2Client GetDataServiceBasic2Client(int minute)
        {
            EndpointAddress endpoint = new EndpointAddress(DataServiceBasic2URL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, minute, 00),
                SendTimeout = new TimeSpan(00, minute, 00),
                OpenTimeout = new TimeSpan(00, minute, 00),
                ReceiveTimeout = new TimeSpan(00, minute, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DataServiceBasic2.DataServicesBasic2Client(binding, endpoint);

            //return new DataServiceBasic2.DataServicesBasic2Client();
        }
        public static DataService.DataServicesClient GetDataServiceClient(int minute)
        {
            EndpointAddress endpoint = new EndpointAddress(DataServicesURL);
            BasicHttpSecurityMode mode = BasicHttpSecurityMode.None;

            if (endpoint.Uri.Scheme.Equals("https"))
                mode = BasicHttpSecurityMode.Transport;

            BasicHttpBinding binding = new BasicHttpBinding(mode)
            {
                CloseTimeout = new TimeSpan(00, minute, 00),
                SendTimeout = new TimeSpan(00, minute, 00),
                OpenTimeout = new TimeSpan(00, minute, 00),
                ReceiveTimeout = new TimeSpan(00, minute, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            binding.Security.Mode = mode;
            return new DataService.DataServicesClient(binding, endpoint);

            //var client = new DataService.DataServicesClient();
            //Channel.AsDisposable(client);
            //return client;
        }




        //public static CloudService.CloudServiceClient GetCloudServiceClient()
        //{
        //    return new CloudService.CloudServiceClient();
        //}
        //public static MailService.MailServiceClient GetMailServiceClient()
        //{


        //    EndpointAddress address = new EndpointAddress("../MailService/MailService.svc");// /* relative service endpoint address */);
        //    //EndpointAddress address = new EndpointAddress("http://demo.viennaadvantage.com/MailService/MailService.svc");// /* relative service endpoint address */);

        //    //PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding(PollingDuplexMode.MultipleMessagesPerPoll);
        //    PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding(PollingDuplexMode.SingleMessagePerPoll)
        //    {

        //        MaxBufferSize = int.MaxValue,
        //        MaxReceivedMessageSize = int.MaxValue,

        //        OpenTimeout = TimeSpan.FromMinutes(10),
        //        SendTimeout = TimeSpan.FromMinutes(10),
        //        CloseTimeout = TimeSpan.FromMinutes(10),


        //        ReceiveTimeout = TimeSpan.FromMinutes(10),
        //        InactivityTimeout = TimeSpan.FromMinutes(10),

        //        // ReceiveTimeout = TimeSpan.FromMinutes(2),
        //        // InactivityTimeout = TimeSpan.FromMinutes(5)

        //    };
        //    return new MailService.MailServiceClient(binding, address);
        //}

        public static NewMailService.MailServiceClient GetNewMailServiceClient()
        {


            EndpointAddress address = new EndpointAddress("../MailService/NewMailService.svc");// /* relative service endpoint address */);
            //EndpointAddress address = new EndpointAddress("http://demo.viennaadvantage.com/MailService/MailService.svc");// /* relative service endpoint address */);

            //PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding(PollingDuplexMode.MultipleMessagesPerPoll);
            PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding(PollingDuplexMode.SingleMessagePerPoll)
            {

                MaxBufferSize = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,

                OpenTimeout = TimeSpan.FromMinutes(10),
                SendTimeout = TimeSpan.FromMinutes(10),
                CloseTimeout = TimeSpan.FromMinutes(10),


                ReceiveTimeout = TimeSpan.FromMinutes(10),
                InactivityTimeout = TimeSpan.FromMinutes(10),

                // ReceiveTimeout = TimeSpan.FromMinutes(2),
                // InactivityTimeout = TimeSpan.FromMinutes(5)

            };
            return new NewMailService.MailServiceClient(binding, address);
        }

        public static CloudService.ServiceSoapClient GetCloudClient(string CloudURL)
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
            {
                CloseTimeout = new TimeSpan(00, 20, 00),
                SendTimeout = new TimeSpan(00, 20, 00),
                OpenTimeout = new TimeSpan(00, 20, 00),
                ReceiveTimeout = new TimeSpan(00, 20, 00),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };
            return new CloudService.ServiceSoapClient(binding, new EndpointAddress(CloudURL));

        
        }

        //public static AcctService.AccountServiceSoapClient GetAcctServiceClient()
        //{
        //    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
        //    {
        //        CloseTimeout = new TimeSpan(00, 20, 00),
        //        SendTimeout = new TimeSpan(00, 20, 00),
        //        OpenTimeout = new TimeSpan(00, 20, 00),
        //        ReceiveTimeout = new TimeSpan(00, 20, 00),
        //        MaxReceivedMessageSize = int.MaxValue,
        //        MaxBufferSize = int.MaxValue
        //    };
        //    return new AcctService.AccountServiceSoapClient(binding, new EndpointAddress(AcctServiceURL));

        //}


        //public static string Decompress(string compressedText)
        //{
        //    byte[] gzBuffer = Convert.FromBase64String(compressedText);
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        int msgLength = BitConverter.ToInt32(gzBuffer, 0);
        //        ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

        //        byte[] buffer = new byte[msgLength];


        //        ms.Position = 0;
        //        using (DataService.  GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
        //        {
        //            zip.Read(buffer, 0, buffer.Length);
        //        }

        //        return Encoding.UTF8.GetString(buffer);
        //    }
        //}


        public static bool UserRejectQuotaIncrese
        {

            get;
            set;
        }




        internal static void GetInfoPopup()
        {
            // Ctx ctx = Envs.GetCtx();
            // SL4PopupMenu.PopupMenu pop = new SL4PopupMenu.PopupMenu();
            // PopupMenuItem mnu = new SL4PopupMenu.PopupMenuItem("InfoProduct16.png",Msg.GetMsg(ctx, "InfoProduct"),null);
            // //mnu.sh
            // mnu.Click +=ActionPerformed;

            // mnu = new SL4PopupMenu.PopupMenuItem("InfoBPartner.png",Msg.GetMsg(ctx, "InfoBPartner"),null);
            //  mnu.Click +=ActionPerformed;
            // //AddAction("InfoProduct", mView, (Keys.Alt | Keys.I), false);
            //// AddAction("InfoBPartner", mView, ((Keys.Alt | Keys.Shift) | Keys.I), false);
            // if (MRole.GetDefault().IsShowAcct())
            // {
            //     AddAction("InfoAccount", mView, ((Keys.Alt | Keys.Control) | Keys.I), false);

            // }
            // //AEnv.AddMenuItem("InfoSchedule", null, Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // mView.DropDown.Items.Add(new ToolStripSeparator());
            // AEnv.AddMenuItem("InfoOrder", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // AEnv.AddMenuItem("InfoInvoice", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // AEnv.AddMenuItem("InfoInOut", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // AEnv.AddMenuItem("InfoPayment", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // AEnv.AddMenuItem("InfoCashLine", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // AEnv.AddMenuItem("InfoAssignment", "Info", Keys.None, mView, this).Click += new EventHandler(this.ActionPerformed);
            // AEnv.AddMenuItem("InfoAsset", "Info", Keys.None, mView, this).Click += new EventHa

        }



        /// <summary>
        /// Perform action command for common menu items.
        ///	Created in AMenu.createMenu(), VPanel.createMenu(), FormFrame.createMenu()

        /// </summary>
        /// <param name="actionCommand">actionCommand known action command</param>
        /// <param name="WindowNo">current window no</param>
        /// <param name="c">parent</param>
        /// <returns>true if succes</returns>
        public static bool ActionPerformed(String actionCommand, int windowNo, FrameworkElement c)
        {
            MRole role = MRole.GetDefault();


            if (actionCommand.Equals("VisualEditor"))
            {
                //VAdvantage.WindowEditor.VisualEditor frm = new VAdvantage.WindowEditor.VisualEditor();
                //frm.Show();
            }

            //  File Menu   ------------------------
            else if (actionCommand.Equals("PrintScreen"))
            {
                //PrintScreenPainter.printScreen (Env.getFrame(c));
            }
            else if (actionCommand.Equals("ScreenShot"))
            {
                //ScreenShot.createJPEG(Env.getFrame(c), null);
            }
            else if (actionCommand.Equals("Logout"))
            {
                // Splash.ShowSplashScreen();
                //ContainerControl frm = Utility.Envs.GetWindow(0);
                // frm.Hide();
                // log.Info("Application Logged out");
                //	End Session
                // MSession session = MSession.Get(Envs.GetContext(), false);	//	finish
                // if (session != null)
                //  session.Logout();

                //Env.Reset(true);

                //VAdvantage.Framework.VLogin login = new VAdvantage.Framework.VLogin();
                //VAdvantage.Apps.AMenu menu = new VAdvantage.Apps.AMenu();
                //Login.Show();

                // Application.Run(new VAdvantage.Apps.AMenu());

                //VAdvantage.Process.CacheReset c = new CacheReset();
                //c.StartProcess(Envs.GetContext(), 

            }
            //	else if (actionCommand.equals("Report"))
            //	{
            //		AEnv.showCenterScreen (new ProcessStart());
            //	}
            else if (actionCommand.Equals("Exit"))
            {
                //if (ADialog.ask(windowNo, c, "ExitApplication?"))
                // if (ShowMessage.Ask("ExitApplication", null, ""))
                // Utility.Envs.ExitEnv(0);
            }

            //  View Menu   ------------------------
            else if (actionCommand.Equals("InfoProduct"))
            {
                
                Info.ShowProduct(Envs.GetFrame(c), windowNo);

            }
            else if (actionCommand.Equals("InfoBPartner"))
            {
                
                Info.ShowBPartner(Envs.GetFrame(c), windowNo);
            }
            else if (actionCommand.Equals("InfoAsset"))
            {
                
                Info.ShowAsset(Envs.GetFrame(c), windowNo);
            }
            else if (actionCommand.Equals("InfoAccount") && MRole.GetDefault().IsShowAcct())
            {
                VAdvantage.Framework.AcctViewer acctViewer = new AcctViewer();
                Envs.ShowForm(acctViewer);
                
            }
            else if (actionCommand.Equals("InfoSchedule"))
            {
                
            }
            else if (actionCommand.Equals("InfoOrder"))
            {
               
                Info.ShowOrder(Envs.GetFrame(c), windowNo, "");
            }
            else if (actionCommand.Equals("InfoInvoice"))
            {
               
                Info.ShowInvoice(Envs.GetFrame(c), windowNo, "");
            }
            else if (actionCommand.Equals("InfoInOut"))
            {
               
                Info.ShowInOut(Envs.GetFrame(c), windowNo, "");
            }
            else if (actionCommand.Equals("InfoPayment"))
            {
               
                Info.ShowPayment(Envs.GetFrame(c), windowNo, "");
            }
            else if (actionCommand.Equals("InfoCashLine"))
            {
               
                Info.ShowCashLine(Envs.GetFrame(c), windowNo, "");
            }
            else if (actionCommand.Equals("InfoAssignment"))
            {
                //Search.Info.showAssignment(Env.getFrame(c), WindowNo, "");
                //Info.ShowAssignment(this, _windowNo, "");
            }

            //  Go Menu     ------------------------
            else if (actionCommand.Equals("WorkFlow"))
            {
                StartWorkflowProcess(0, 0);
            }
            else if (actionCommand.Equals("Home"))
            {
                //ContainerControl frm = Utility.Envs.GetWindow(0);
                // if (frm is Form)
                // {
                //     ((Form)frm).Activate();
                //     frm.BringToFront();
                // }
                // frm = null;
            }

            //  Tools Menu  ------------------------
            else if (actionCommand.Equals("Calculator"))
            {
                //AEnv.showCenterScreen (new Calculator(Env.getFrame(c)));
            }
            else if (actionCommand.Equals("Calendar"))
            {
                //AEnv.showCenterScreen (Calendar(Env.getFrame(c)));
            }
            else if (actionCommand.Equals("Editor"))
            {
                //new Framework.Editor().ShowDialog();
                //AEnv.showCenterScreen (new Editor(Env.getFrame(c)));
            }
            else if (actionCommand.Equals("Script"))
            {
                //new ScriptEditor();
            }
            else if (actionCommand.Equals("Preference"))
            {
                if (role.IsShowPreference())
                {
                    //AEnv.showCenterScreen(new Preference (Env.getFrame(c), WindowNo));
                    VAdvantage.Framework.UserPreference frm = new VAdvantage.Framework.UserPreference();
                    Utility.Envs.RegisterWindowForm(frm);
                    frm.Show();
                }
            }

            //  Help Menu   ------------------------
            else if (actionCommand.Equals("Online"))
            {
                //Env.startBrowser(Vienna.GetURL());
            }
            else if (actionCommand.Equals("EMailSupport"))
            {
                //ADialog.createSupportEMail(Env.getFrame(c), Env.getFrame(c).getTitle(), "\n\n");
                //VAdvantage.Framework.EMailDialog email = new VAdvantage.Framework.EMailDialog(VAdvantage.Model.MUser.Get(VAdvantage.Utility.Envs.GetContext()), Msg.GetMsg(Envs.GetContext(), "EMailSupport"), "", Env.GetForm(c).Text, VAdvantage.Logging.VLogErrorBuffer.Get(true).GetErrorInfo(VAdvantage.Utility.Envs.GetContext(), false));
                //FixedWinTemp objEmail = new FixedWinTemp("", "", content);
                // email.Show();
            }
            else if (actionCommand.Equals("About"))
            {
                //AEnv.showCenterScreen(new AboutBox(Env.getFrame(c)));
            }
            else
                return false;
            //
            return true;
        }


        internal static TextBlock GetDataGridElement()
        {
            TextBlock txt = new TextBlock();
            txt.Margin = new Thickness(3, 0, 2, 0);
            txt.VerticalAlignment = VerticalAlignment.Center;
            txt.FontSize = 10.5;
            txt.Foreground = new SolidColorBrush(Color.FromArgb(255, 59, 59, 59));
            txt.TextWrapping = TextWrapping.Wrap;
            return txt;
        }
        public static void Reset()
        {
            
        /** Workflow Menu		*/
         _workflow = null;
        /** Workflow Menu		*/
         workflowWindowID = 0;

        /**	Window Cache		*/
         CCache<int, GridWindowVO> s_windows
            = new CCache<int, GridWindowVO>("AD_Window", 10);

        /* SilverLight Window Cache */
        /* Sales Order ,Request,Lead, Product etc*/

        //DO NOT CHANGE WEATHER SERVICE PATH
         GlobalWeatherURL = "http://www.webservicex.net/globalweather.asmx";
         CountryURL = "http://www.webservicex.net/country.asmx";

       
                log = VLogger.GetVLogger(typeof(AEnv).FullName);
               _isEmployee = null;
               _workflow = null;

        }

    }
}
